const { Api } = require("./api");

const app = getApp()

function post(url, params, onSuccess, onFailed=defaultFailed) {
  request(url, params, "POST", onSuccess, onFailed, true);
}

function get(url, params, onSuccess, onFailed=defaultFailed) {
  request(url, params, "GET", onSuccess, onFailed, true);
}

function put(url, params, onSuccess, onFailed=defaultFailed) {
  request(url, params, "PUT", onSuccess, onFailed, true);
}

function defaultFailed(res) {
}
/**
 * function: 封装网络请求
 * @url URL地址
 * @params 请求参数
 * @method 请求方式：GET/POST
 * @onSuccess 成功回调
 * @onFailed  失败回调
 */
function request(url, params, method, onSuccess, onFailed, isNeedGoToLogin) {
  let header = {}
  if (method === 'POST') {
    header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  }
  if (!url) {
    wx.showToast({title: '接口异常', icon: 'none'})
    return
  }
  wx.request({
    url: Api.http + url,
    data: dealParams(params),
    method: method,
    header: header,
    success: function (res) {
      if (res.data) {
        if (res.data.success) {
          onSuccess(res.data);
        } else if (res.data.code == 500) {
          wx.showToast({
            title: res.data.msg || '系统异常',
            icon: 'none'
          })
          setTimeout(() => {
            onFailed(res);
          }, 500);
        } else if (res.data.code == 401) {
          wx.navigateTo({url: '/pages/login/login'})
        } else if (res.data.code == 402) {
          wx.navigateTo({url: '/pages/account/account'})
        } else {
          wx.showToast({
            title: res.data.msg || '系统异常',
            icon: 'none'
          })
        }
      } else {
        wx.showToast({
          title: res.data.msg || '系统异常',
          icon: 'none'
        })
        console.error()
      }
    },
    fail: function (error) {
      console.log(error)
      wx.hideLoading()
      onFailed(error);
    }
  })
}

/**
 * function: 根据需求处理请求参数：添加固定参数配置等
 * @params 请求参数
 */
function dealParams(params) {
  params['token'] = wx.getStorageSync('token')
  //过滤undefined和null
  for (let key in params) {
      if (params[key] === undefined || params[key] === null || params[key] === '') {
      delete params[key]
      }
  }
  return params;
}


// 1.通过module.exports方式提供给外部调用
module.exports = {
  postRequest: post,
  getRequest: get,
  putRequest: put,
}
